#include"http.hpp"

#define WWWROOT "./wwwroot/"

//回显
string RequestStr(const HttpRequest& req)
{
    stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for(auto& it : req._params) //查询字符串
    {
        ss << it.first << "=" << it.second << "\r\n";
    }
    for(auto& it:req._headers)
    {
         ss << it.first <<  ":" << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}

void Hello(const HttpRequest& req,HttpResponse* rsp)
{
    DBG_LOG("come hello");
    rsp->SetContent(RequestStr(req),"text/plain");
    //sleep(15);
}

void Login(const HttpRequest& req,HttpResponse* rsp)
{
    DBG_LOG("come login");
   rsp->SetContent(RequestStr(req),"text/plain");
}

void PutFile(const HttpRequest& req,HttpResponse* rsp)
{
    DBG_LOG("come PutFile");
//    rsp->SetContent(RequestStr(req),"text/plain");

   string pathname = WWWROOT + req._path;
   cout <<  "pathname: " << pathname << endl;
   std::cout << "body size():" << req._body.size() << endl;
   cout << "body:" << req._body << endl;
   Util::WriteFile(pathname,req._body);
}

void DeleteFile(const HttpRequest& req,HttpResponse* rsp)
{
    DBG_LOG("come DeleteFile");
   rsp->SetContent(RequestStr(req),"text/plain");
}

int main()
{
    HttpServer server(8085);
    server.SetThreadCount(3);
    server.SetBaseDir(WWWROOT);//设置静态资源，告诉服务器有静态资源请求到来，需要到哪里去寻找资源文件
    server.Get("/hello",Hello);
    server.Post("/login",Login);
    server.Put("/1234.txt",PutFile);
    server.Delete("/1234.txt",DeleteFile);
    server.EnableInactiveRelease(10);
    server.Listen();
    return 0;
}
